from playwright.async_api import async_playwright
from playwright._impl._api_structures import ProxySettings
from typing import TypedDict, Optional

class PageArgs(TypedDict):
    executable_path: Optional[str]
    headless: Optional[bool]
    proxy: Optional[ProxySettings]
    user_agent: Optional[str]
    args: Optional[list]

class AsyncBrowser:
    async def init_browser(self, page_args: PageArgs):
        self.playwright = await async_playwright().start()
        self.browser = await self.playwright.chromium.launch(
            executable_path=page_args.get('executable_path', None),
            headless=page_args.get('headless', False),
            proxy=page_args.get('proxy', None),
            args=page_args.get('args', None)
        )
        self.context = await self.browser.new_context(
            user_agent=page_args.get('user_agent', None),
            proxy=page_args.get('proxy', None)
        )
        self.page = await self.context.new_page()

        async def intercept_resources(route):
            if route.request.resource_type in ["stylesheet", "image"]:
                await route.abort()
            else:
                await route.continue_()
                
        await self.page.route("**/*", intercept_resources)
        
    async def close(self):
        if hasattr(self, 'context'):
            await self.context.close()
        if hasattr(self, 'browser'):
            await self.browser.close()
        if hasattr(self, 'playwright'):
            await self.playwright.stop()
            